/* Copyright 2013 Agustina Martinez-Garcia

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 * */
var collectionsJSON;
var filesJSON;
var categoriesJSON;

function toggleCollection(element) {
	var ele = element.parentNode;

	if (ele != null) {
		var divArray = ele.getElementsByTagName('div');
		var div = divArray[0];
		if (div.style.display == "block") {
			div.style.display = "none";
			element.innerHTML = 'More <img src="./images/Expand.png">';
		} else {
			div.style.display = "block";
			element.innerHTML = 'Less <img src="./images/Collapse.png">';
		}
	} else
		alert("DIV not found");
}

function toggleFile(element) {
	var ele = element.parentNode;

	if (ele != null) {
		var divArray = ele.getElementsByTagName('div');
		var div = divArray[0];
		if (div.style.display == "block") {
			div.style.display = "none";
			element.innerHTML = 'What are this item&#39;s related files? <img src="./images/Expand.png">';
		} else {
			div.style.display = "block";
			element.innerHTML = 'Collapse <img src="./images/Collapse.png">';
		}
	} else
		alert("DIV not found");
}

function getCollections(json) {
	collectionsJSON = json;
	return json;
}

function getFiles(json) {
	filesJSON = json;
	for ( var x in filesJSON.items) {
		var file = filesJSON.items[x];
		if (file.hasOwnProperty('isDocumentationOf')) {
			if (Object.prototype.toString.call(file.isDocumentationOf) === '[object Array]') {
				for (var j in file.isDocumentationOf)
					file.isDocumentationOf[j] = file.isDocumentationOf[j].replace("info:fedora/", "");
			}
			else file.isDocumentationOf = file.isDocumentationOf.replace("info:fedora/", "");
		}
		if (file.hasOwnProperty('isRelatedTo')) {
			if (Object.prototype.toString.call(file.isRelatedTo) === '[object Array]') {
				for (var j in file.isRelatedTo)
					file.isRelatedTo[j] = file.isRelatedTo[j].replace("info:fedora/", "");
			}
			else file.isRelatedTo = file.isRelatedTo.replace("info:fedora/", "");
		}
		if (file.hasOwnProperty('isAnnotationOf')) {
			if (Object.prototype.toString.call(file.isAnnotationOf) === '[object Array]') {
				for (var j in file.isAnnotationOf)
					file.isAnnotationOf[j] = file.isAnnotationOf[j].replace("info:fedora/", "");
			}
			else file.isAnnotationOf = file.isAnnotationOf.replace("info:fedora/", "");
		}
		if (file.hasOwnProperty('isFormatOf')) {
			if (Object.prototype.toString.call(file.isFormatOf) === '[object Array]') {
				for (var j in file.isFormatOf)
					file.isFormatOf[j] = file.isFormatOf[j].replace("info:fedora/", "");
			}
			else file.isFormatOf = file.isFormatOf.replace("info:fedora/", "");
		}
		if (file.hasOwnProperty('isVersionOf')) {
			if (Object.prototype.toString.call(file.isVersionOf) === '[object Array]') {
				for (var j in file.isVersionOf)
					file.isVersionOf[j] = file.isVersionOf[j].replace("info:fedora/", "");
			}
			else file.isVersionOf = file.isVersionOf.replace("info:fedora/", "");
		}
		if (file.hasOwnProperty('isReferencedBy')) {
			if (Object.prototype.toString.call(file.isReferencedBy) === '[object Array]') {
				for (var j in file.isReferencedBy)
					file.isReferencedBy[j] = file.isReferencedBy[j].replace("info:fedora/", "");
			}
			else file.isReferencedBy = file.isReferencedBy.replace("info:fedora/", "");
		}
		// Just in case the values from the spreadsheet are in Upper case
		file.is_original = file.is_original.toLowerCase();
		file.ident = file.id;
	}
	return json;
}
var hash = function(obj) {
	// collection or file + qudex:XXX
	return obj.type + ': ' + obj.identifier; // just an example
};
// Construct node hash
function constructHash(collectionId) {
	var dict = {};
	// dict[hash(obj1)] = obj1;
	for ( var x in filesJSON) {
		var file = filesJSON[x];
		var parents = file.relation;
		for ( var id in parents) {
			if (id == collectionId) {
				dict[hash(file)] = file.hasAnnotation;
				break;
			}
		}
	}
	return dict;
}
/* Functions associated with the Graph page */
/*
 * post a form with the parameters needed to generate the JSON data either for A
 * file graph or a collection graph
 */
function post(url, method, colId, type) {
	method = method || "post"; // post (set to default) or get
	var myDictionary = [];
	// Create the form object
	var form = document.createElement("form");
	if (type == 'collection') {
		myDictionary["collections"] = JSON.stringify(collectionsJSON);
		myDictionary["files"] = JSON.stringify(filesJSON);
		myDictionary["cats"] = JSON.stringify(categoriesJSON);
		myDictionary["colIdx"] = findColIndex(colId);
	} else {
		myDictionary["files"] = JSON.stringify(filesJSON);
		myDictionary["cats"] = JSON.stringify(categoriesJSON);
		myDictionary["colIdx"] = findFileIndex(colId);
		// Extra form field to specify that we are creating a file graph instead
		// of a collection one
		var hiddenField = document.createElement("input");
		hiddenField.setAttribute("type", "hidden"); // 'hidden' field to send
		// the information
		hiddenField.setAttribute("name", "type");
		hiddenField.setAttribute("value", "file");
		form.appendChild(hiddenField); // append the newly created control to
		// the form
	}

	form.setAttribute("target", "_blank");
	form.setAttribute("method", method);
	form.setAttribute("action", url);

	// For each key-value pair
	for (key in myDictionary) {
		// alert('key: ' + key + ', value:' + dictionary[key]); // debug
		var hiddenField = document.createElement("input");
		hiddenField.setAttribute("type", "hidden"); // 'hidden' field to send
		// the information
		hiddenField.setAttribute("name", key);
		hiddenField.setAttribute("value", myDictionary[key]);
		form.appendChild(hiddenField); // append the newly created control to
		// the form
	}

	document.body.appendChild(form); // inject the form object into the body
	// section
	form.submit();
}

// Find the index of the collection that is the source of the graph page
function findColIndex(id) {
	var collections = collectionsJSON.items;
	for ( var x in collections) {
		var collection = collections[x];
		if (collection.identifier == id) {
			return x;
		}
	}
}
// Find the index of the file that is the source of the graph page
function findFileIndex(id) {
	var files = filesJSON.items;
	for ( var x in files) {
		var file = files[x];
		if (file.ident == id) {
			return x;
		}
	}
}
/* END of auxiliar functions for the graph page */

/*
 * For the hierarchical facet, create the category elements, to generate the
 * Categories hierarchical facet
 */
function generateCategoryStructure(json) {
	categoriesJSON = json;
	var categories = json.items;
	for ( var x in categories) {
		var category = categories[x];
		if (category.cat_parent_label) {
			var cat_label = category.label.substring(category.label
					.lastIndexOf(':') + 1, category.label.length);
			categories.push({
				id : category.cat_parent_label,
				type : "CategorySubject",
				label : category.cat_parent_label
			});
			categories.push({
				id : cat_label,
				type : "CategorySubject",
				label : cat_label,
				subTopicOf : category.cat_parent_label
			});
		}
	}

	return json;
}

function loadDatos(url) {
	var xobj = new XMLHttpRequest();
	// xobj.overrideMimeType("application/json");
	xobj.open('GET', url, true);
	xobj.onreadystatechange = function() {
		if (xobj.readyState == 4) {
			convertJson(xobj.responseText, "", "");
		}
	};
	xobj.send(null);
}
function convertJson(json, keyTranslate, keyAdd) {
	var ipJson = eval("(" + json + ')');
	alert(ipJson.head);
	// Keep track of types
	var types = new Array();
	for (col in ipJson.head.vars) {
		types[col] = "";
	}

	// Walk items
	var intermediateItems = [];
	for ( var idx = 0; idx < ipJson.results.bindings.length; idx++) {
		var b = ipJson.results.bindings[idx];
		var o = new Object();
		for (key in b) {
			// If ex:converterTranslateKeys has an entry for this key, use
			// alternative
			// var transKey = (keyTranslate[key] != undefined) ?
			// keyTranslate[key] : key ;
			// Store value
			o[key] = b[key].value;
			if (types[key] == "") {
				types[key] = type;
			}
			// console.log(key);
		}
		// If ex:converterAddKeys has entries, set them
		for (key in keyAdd) {
			o[key] = keyAdd[key];
		}
		intermediateItems.push(o);
		// console.log(o);
	}

	// Merge duplicates : find items with same id, merge properties into arrays
	var itemsById = {};
	for ( var idx = 0; idx < intermediateItems.length; idx++) {
		var id = intermediateItems[idx].id;
		if (!itemsById[id]) {
			itemsById[id] = [];
		} // Not known? Create array
		itemsById[id].push(intermediateItems[idx]); // Add
	}
	var opItems = [];
	for ( var id in itemsById) {
		var items = itemsById[id];
		if (items.length <= 1) {
			// Only one item, store unmerged
			opItems.push(items[0]);
		} else {
			// Multiple items with same id, merge *unique* properties
			var opItem = {};
			for ( var idx = 0; idx < items.length; idx++) { // For each item
				// with same id
				var nthItem = items[idx];
				for ( var p in nthItem) { // For each property
					if (!opItem[p]) {
						opItem[p] = [];
					} // Create prop as array
					var cnt = 0;
					for ( var z = 0; z < opItem[p].length; z++) {
						cnt += (opItem[p][z] == nthItem[p]) ? 1 : 0;
					}
					if (!cnt) {
						opItem[p].push(nthItem[p]);
					} // Copy if not already
				}
			}
			// Turn all single sized arrays into scalars (not strictly
			// necessary, but neater)
			for ( var p in opItem) {
				if (opItem[p].length == 1) {
					opItem[p] = opItem[p][0];
				}
			}
			opItems.push(opItem);
		}
	}

	var opJson = {
		items : opItems
	};
	console.log(JSON.stringify(opJson));
	return opJson;
};
/* Functions for the Save Track functionality */
// Extract parameters from the URL
function getUrlParam() {
	// var strReturn = "";
	var queryStringList = {};
	queryStringList.label = function() {
		var lab = "";
		for ( var i in this) {
			// alert(i);
			if ((i != "size") && (i != "label")) {
				lab += this[i] + ", ";
			}
		}
		// alert ("queryStringLabel: " + lab);
		return lab.substr(0, lab.length - 2);
		;
	};

	queryStringList.size = function() {
		var size = 0;
		for ( var i in this) {
			// alert(this[i]);
			size++;
		}
		return size - 2;
	};

	var strHref = window.location.href;
	// var pos = strHref.indexOf("?");
	var pos = strHref.indexOf("#");
	if (pos > -1) {

		var strQueryString = strHref.substr(pos + 1);
		var aQueryString = strQueryString.split("&");
		for ( var iParam = 0; iParam < aQueryString.length; iParam++) {
			var aParam = aQueryString[iParam].split("=");
			queryStringList[aParam[0]] = unescape(aParam[1]);
		} // for
	} // if
	// alert("getUrlParam: " + queryStringList.size());
	return queryStringList;
}
// Set Exhibit filters based on the URL parameters
function setFilters() {
	// console.time("setFilters");
	SimileAjax.jQuery(document).ready(function() {
		var fDone = function() {
			window.exhibit = Exhibit.create();
			window.exhibit.configureFromDOM();
			overrideFacetApplyRestriction();
			overrideFacetClearAllRestrictions();
			applyMyRestrictions();
		}; // function fDone

		try {
			var s = Exhibit.getAttribute(document.body, "ondataload");
			if (s != null && typeof s == "string" && s.length > 0) {
				fDone = function() {
					var f = eval(s);
					if (typeof f == "function") {
						f.call();
					} // if

				}; // function
			} // if
		} catch (e) {
		}
		window.database = Exhibit.Database.create();
		window.database.loadDataLinks(fDone);
	}); // ready( function(){...});

	// console.timeEnd("setFilters");

} // setFilters

function overrideFacetClearAllRestrictions() {
	var oldClearR = Exhibit.ListFacet.prototype.clearAllRestrictions;
	Exhibit.ListFacet.prototype.clearAllRestrictions = function() {
		oldClearR.call(this);
		var p = document.getElementById("fil");
		p.textContent = "";
		p.innerHTML = "<br>";
	};
}

function overrideFacetApplyRestriction() {
	var oldApplyRestrictions = Exhibit.ListFacet.prototype.applyRestrictions;
	Exhibit.ListFacet.prototype.applyRestrictions = function(restrictions) {
		oldApplyRestrictions.call(this, restrictions);
		var p = document.getElementById("fil");
		var selected = "";
		for ( var i = 0; i < restrictions.selection.length; i++) {
			selected += restrictions.selection[i] + " ";
		}
		if (i > 0) {
			p.textContent = "Data has been loaded with the following filters set: "
					+ selected;
		} else {
			p.textContent = "";
			p.innerHTML = "<br>";
		}
	};
}

function applyMyRestrictions() {
	var selection = getUrlParam();
	if (selection.size() > 0) {
		for ( var i in selection) {
			if ((i != "size") && (i != "label")) {
				var filter = selection[i].split(";");
				var facet = window.exhibit.getComponent(i);
				var newRestrictions = {
					selection : filter,
					selectMissing : false
				};
				facet.applyRestrictions(newRestrictions);
			}// if i
		} // for
	} // if selection

}// overrideApplyRestrictions
function saveSearch() {
	var data = {};

	// Getting the selected values for an specific facet
	data.subjectf = window.exhibit.getComponent("subjectf")._valueSet.toArray();
	data.codef = window.exhibit.getComponent("codef")._valueSet.toArray();
	// data.catf = window.exhibit.getComponent("catf")._selections;
	data.typef = window.exhibit.getComponent("typef")._valueSet.toArray();
	data.formatf = window.exhibit.getComponent("formatf")._valueSet.toArray();
	data.colelemf = window.exhibit.getComponent("colelemf")._valueSet.toArray();
	// console.dir(data);
	var querystring = EncodeQueryData(data);
	console.dir(querystring);

	var strhref = window.location.href;

	var pos = strhref.indexOf("#");
	if (pos > -1) {
		strhref = strhref.substr(0, pos);
	}
	var colbit = strhref.indexOf('?collection') == -1 ? "?collection="
			+ document.getElementById("collectionid").value : "";
	// http://json-tinyurl.appspot.com/?
	var url = 'http://urltinyfy.appspot.com/tinyurl?url='
			+ encodeURIComponent(strhref + colbit + '#' + querystring)
			+ '&callback=?';
	/* NOT USED */
	/*
	 * requestShortURL(url, function(shortened){ tiny = resp.tinyurl;
	 * $("#url").val(tiny); ShowDialog(true); console.dir(tiny); });
	 */

	// Obtaining a Tinyurl for the pre-filtered search
	// http://tinyurl.com/api-create.php?url=my-url
	$.getJSON(url, function(resp) {
		tiny = resp.tinyurl;
		$("#url").val(tiny);
		ShowDialog(true);
		console.dir(tiny);
	});
}
/* NOT USED */
function requestShortURL(longURL, success) {

	var API = 'http://reque.st/create.api.php?json&url=', URL = API
			+ encodeURIComponent(longURL) + '&callback=?';

	$.getJSON(URL, function(data) {
		success && success(data.url);
	});

}

function EncodeQueryData(data) {
	var ret = [];
	for ( var d in data)
		for ( var avalue in data[d])
			ret.push(encodeURIComponent(d) + "="
					+ encodeURIComponent(data[d][avalue]));
	return ret.join("&");
}

// SHOW DIALOGS
function ShowDialog(modal) {
	$("#overlay").show();
	$("#dialog").fadeIn(300);

	if (modal) {
		$("#overlay").unbind("click");
	} else {
		$("#overlay").click(function(e) {
			HideDialog();
		});
	}
}

function HideDialog() {
	$("#overlay").hide();
	$("#dialog").fadeOut(300);
}